package com.chiasma.writogether.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.chiasma.writogether.jdo.PMF;
import com.chiasma.writogether.model.Entries;
import com.chiasma.writogether.rpc.WritogetherService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class WritogetherServiceImpl extends RemoteServiceServlet implements WritogetherService {

	
	@SuppressWarnings({ "unchecked", "deprecation" })
	public List<Entries> getAllEntries() throws Exception {
		List<Entries> entriesList = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Date restrictedCreateDate = new Date("Mon Jan 01 00:00:00 UTC 2010");
		Query query = pm.newQuery(Entries.class);
		try {
			
			query.setFilter("createDate > restrictCreateDate");
			query.declareImports("import java.util.Date");
		    query.declareParameters("Date restrictCreateDate");
		    query.setOrdering("createDate asc");
		    
			entriesList = new ArrayList<Entries>();
			entriesList = (List<Entries>)query.execute(restrictedCreateDate);
			
			//System.out.println(query);

		}finally {
			query.closeAll();
			//pm.close();
		}
		
		//System.out.println("Size of entriesList :"+entriesList.size());
		
		//Dumping the entriesList from Persistence Level to Code Level
		List<Entries> tempList = new ArrayList<Entries>();
		for (Entries e: entriesList) {
			tempList.add(e);			
		}
		//System.out.println("Size of tempList :"+tempList.size());
		return tempList;
	}
	
	
	public Boolean createNewEntries(String currentUserNickname, String entries) throws Exception {
		
		Boolean status = new Boolean(false);
		Entries entry = new Entries();
	
		entry.setWriterName(currentUserNickname);
		entry.setEntryContent(entries);
		entry.setCreateDate(new Date());
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(entry);
			status = true;
		}catch(Exception ex) {
			ex.printStackTrace();
			
		}finally {
			pm.close();
		}
		
		return status;
	}
}
